﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Common.IProviders;
using System.Web;
using System.Configuration;
using CSP.Common.Tools;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using CSP.Common.Factories;

namespace CSP.Common.Providers
{
    public class QQConnectApiProvider : OtherApiProvider
    {
        public override string AccessToken
        {
            get
            {
                if (HttpContext.Current.Session["OtherAccessToken"] != null)
                {
                    return HttpContext.Current.Session["OtherAccessToken"].ToString();
                }
                return "";
            }
            set
            {
                HttpContext.Current.Session["OtherAccessToken"] = value;
            }
        }


        /// <summary>
        /// QQ互联AppKey
        /// </summary>
        public string QQConnectUid
        {
            get
            {
                return ConfigurationManager.AppSettings["QQConnectUid"];
            }
        }

        /// <summary>
        /// QQ互联AppKey
        /// </summary>
        public string QQConnectKey
        {
            get
            {
                return ConfigurationManager.AppSettings["QQConnectKey"];
            }
        }

        /// <summary>
        /// QQ互联AppId
        /// </summary>
        public string QQConnectAppId
        {
            get
            {
                return ConfigurationManager.AppSettings["QQConnectAppId"];
            }
        }


        /// <summary>
        /// 新浪微博登陆跳转授权
        /// </summary>
        public string QQConnectAuthorizeUri
        {
            get
            {
                return ConfigurationManager.AppSettings["QQConnectAuthorize"];
            }
        }

        /// <summary>
        /// 新浪微博获取获取授权Uri
        /// </summary>
        public string QQConnectAccessTokenUri
        {
            get
            {
                return ConfigurationManager.AppSettings["QQConnectAccessToken"];
            }
        }

        ///// <summary>
        ///// 新浪微博授权查询
        ///// </summary>
        //public string SinaWeiBoGetTokenInfoUri
        //{
        //    get
        //    {
        //        return ConfigurationManager.AppSettings["SinaWeiBoGetTokenInfo"];
        //    }
        //}

        /// <summary>
        /// QQ互联分享到控件并分享到微博
        /// </summary>
        public string QQConnectPublishShareUri
        {
            get
            {
                return ConfigurationManager.AppSettings["QQConnectPublishShare"];
            }
        }

        /// <summary>
        /// 营销标题
        /// </summary>
        private string MarketingMsg
        {
            get
            {
                return ConfigurationManager.AppSettings["MarketingMsg"];
            }
        }

        /// <summary>
        /// 营销描述
        /// </summary>
        private string MarketingDescription
        {
            get
            {
                return ConfigurationManager.AppSettings["MarketingDescription"];
            }
        }

        /// <summary>
        /// QQ互联发布微博
        /// </summary>
        public string QQConnectPublishInfoUri
        {
            get
            {
                return ConfigurationManager.AppSettings["QQConnectPublishInfo"];
            }
        }

        /// <summary>
        /// QQ互联关注微博
        /// </summary>
        public string QQConnectAttentionUri
        {
            get
            {
                return ConfigurationManager.AppSettings["QQConnectAttention"];
            }
        }

        /// <summary>
        /// 获取QQ互联用户信息
        /// </summary>
        public string QQConnectUserInfoUri
        {
            get
            {
                return ConfigurationManager.AppSettings["QQConnectUserInfo"];
            }
        }

        /// <summary>
        /// QQ互联获取Token信息
        /// </summary>
        public string QQConnectGetTokenInfoUri
        {
            get
            {
                return ConfigurationManager.AppSettings["QQConnectGetTokenInfo"];
            }
        }


        /// <summary>
        /// 用户Id
        /// </summary>
        public override string Uid
        {
            get
            {

                if (HttpContext.Current.Session["otherUid"] != null)
                {
                    return HttpContext.Current.Session["otherUid"].ToString();
                }
                else {
                    return "";
                }
                
            }
            protected set 
            {
                HttpContext.Current.Session["otherUid"] = value;
            }
        }

        /// <summary>
        /// 请求API登陆授权
        /// </summary>
        /// <returns></returns>
        public override void RequestApiAuthorization(string backUrl)
        {

            string requestUrl = QQConnectAuthorizeUri + "?response_type=code&state=tongshuya&scope=get_user_info,get_idollist,add_share,add_t,add_idol&client_id=" + QQConnectAppId + "&redirect_uri=" + HttpContext.Current.Server.UrlEncode(backUrl);
            HttpContext.Current.Response.Redirect(requestUrl);
        }

        /// <summary>
        /// 根据请求的Code值，和重定向的Uri获取用户基本信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="redirectUri"></param>
        /// <returns></returns>
        public override Dictionary<string, string> GetUserInfo(string code, string redirectUri, string openId = "")
        {
            GetAccessToken(code, redirectUri);
            Dictionary<string,string> tokenInfo=GetTokenInfoByToken(AccessToken);
            Uid = tokenInfo["openid"];
            Dictionary<string, string> result = GetUserInfoByAccessToken(AccessToken, Uid);
            return result;
        }

        /// <summary>
        ///Api事件处理管道“关注/微博”
        /// </summary>
        /// <param name="isPublish"></param>
        /// <param name="isAttention"></param>
        public override void EventHandling(bool isPublish, bool isAttention)
        {
            if (isPublish)
            {
                PublishInfo();
            }

            if (isAttention)
            {
                Attention();
            }
        }

        /// <summary>
        /// 获取权限令牌AccessToken
        /// </summary>
        /// <param name="code">新浪Code</param>
        /// <param name="redirectUri">回调的链接地址</param>
        /// <returns></returns>
        private void GetAccessToken(string code, string redirectUri)
        {
            string redirecturl = "client_id=" + QQConnectAppId + "&client_secret=" + QQConnectKey + "&grant_type=authorization_code" +
                    "&code=" + code + "&redirect_uri=" +HttpContext.Current.Server.UrlEncode( redirectUri);
            string json = CommonTool.MakePostByUrlAndPostData(QQConnectAccessTokenUri, redirecturl);
            Dictionary<string, string> accessToken = AnalysisQQConnectAccessToken(json);
            string access_token = accessToken["access_token"];
            AccessToken = access_token;


        }

        private Dictionary<string, string> GetTokenInfoByToken(string accessToken) {
            Dictionary<string, string> result = new Dictionary<string, string>();
            string getTokenInfoUrl=QQConnectGetTokenInfoUri;
            string redirecturl = getTokenInfoUrl + "?access_token=" + accessToken;
            string json = CommonTool.MakeGetByUrl(redirecturl);
            result = AnalysisQQConnectAccessTokenInfo(json);
            return result;
        }

        /// <summary>
        /// 根据AccessToken获取用户信息
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetUserInfoByAccessToken(string accessToken, string uid)
        {
            string getUserInfoUrl = QQConnectUserInfoUri;
            string redirecturl = getUserInfoUrl + "?access_token=" + accessToken + "&openid=" + uid + "&oauth_consumer_key="+QQConnectAppId;
            string json = CommonTool.MakeGetByUrl(redirecturl);
             Dictionary<string, string> jsonDic = AnalysisQQConnectResult(json);
             if (jsonDic["ret"] != "0")
             {
                 ILoggerProvider logger = LoggerFactory.GetErrorLogger();
                 logger.Warn("(警告)QQ互联微博获取用户信息:" + json + "  [openId]:" + Uid + "[Token]:" + AccessToken);
             }
            Dictionary<string, string> result = AnalysisQQConnectGetUserInfo(json);
            return result;
        }

        /// <summary>
        /// 发布信息
        /// </summary>
        private void PublishInfo()
        {
            string qqConnectPublishShareUri = QQConnectPublishShareUri;
            
            string marketingTitle = HttpContext.Current.Server.UrlEncode(MarketingMsg);
            string marketingUrl = HttpContext.Current.Server.UrlEncode("http://www.tongshuya.com");
            string site = HttpContext.Current.Server.UrlEncode("信然贷网");
            string fromurl = HttpContext.Current.Server.UrlEncode("http://www.tongshuya.com");
            string shareRequest = "access_token=" + AccessToken + "&oauth_consumer_key=" + QQConnectKey + "&openid=" + Uid + "&title=" + marketingTitle + "&site=" + site + "&fromurl" + fromurl + "&url=" + marketingUrl + "&client_id=" + QQConnectAppId;
            

            string json = CommonTool.MakePostByUrlAndPostData(qqConnectPublishShareUri, shareRequest);

            Dictionary<string, string> resultDic = AnalysisQQConnectResult(json);
            ILoggerProvider logger = LoggerFactory.GetErrorLogger();
            //如果分享失败则以微博形式发送
            if(resultDic["ret"]!="0"){
                
                logger.Warn("(警告)QQ互联分享空间和微博:" + json + "  [openId]:" + Uid + "[Token]:" + AccessToken);
                string qqConnectPublishInfo = QQConnectPublishInfoUri;
                string marketingMsg = HttpContext.Current.Server.UrlEncode(MarketingMsg+MarketingDescription);
                string qqWeiBoRequest = "access_token=" + AccessToken + "&oauth_consumer_key=" + QQConnectKey + "&openid=" + Uid + "&content=" + marketingMsg + "&client_id=" + QQConnectAppId;
                string weiboJson=CommonTool.MakePostByUrlAndPostData(qqConnectPublishInfo, qqWeiBoRequest);
                resultDic=AnalysisQQConnectResult(weiboJson);

                if (resultDic["ret"] != "0")
                {
                    logger.Warn("(警告)QQ互联发布微博:" + weiboJson + "  [openId]:" + Uid + "[Token]:" + AccessToken);
                }
            }
        }

        /// <summary>
        /// 关注
        /// </summary>
        private void Attention()
        {
            string request;
            //关注
            string sinaWeiBoAttention = QQConnectAttentionUri;
            string uid = QQConnectUid;
            request = "access_token=" + AccessToken + "&oauth_consumer_key=" + QQConnectKey + "&openid=" + Uid + "&name=" + QQConnectUid+"&client_id="+QQConnectAppId;
            string json=CommonTool.MakePostByUrlAndPostData(sinaWeiBoAttention, request);
            Dictionary<string, string> jsonDic = AnalysisQQConnectResult(json);
            if (jsonDic["ret"] != "0")
            {
                ILoggerProvider logger = LoggerFactory.GetErrorLogger();
                logger.Warn("(警告)QQ互联微博关注:" + json + "  [openId]:" + Uid + "[Token]:" + AccessToken);
            }
        }


        /// <summary>
        /// 解析QQ互联获取授权
        /// </summary>
        /// <param name="json"></param>
        private Dictionary<string, string> AnalysisQQConnectAccessToken(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            //JObject obj = (JObject)JsonConvert.DeserializeObject(json);

            string temJson = json.Replace("access_token=","");
            int endTokenIndex = temJson.IndexOf("&");
            string access_token = temJson.Substring(0,endTokenIndex);
            string expires_in = temJson.Substring(endTokenIndex +11,temJson.Length-(endTokenIndex +11));
            
            //权限token;
            dic.Add("access_token", access_token);
            dic.Add("expires_in", expires_in);

            return dic;
        }

        /// <summary>
        /// 解析Token信息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private Dictionary<string, string> AnalysisQQConnectAccessTokenInfo(string json)
        {
            string temJson = json.Replace("callback(","").Replace(")","").Replace("\n","").Replace(";","");
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(temJson);
            //权限token
            string client_id = obj["client_id"].ToString().Replace("\"", "");
            string openid = obj["openid"].ToString().Replace("\"", "");
            dic.Add("client_id", client_id);
            dic.Add("openid", openid);
            return dic;
        }

        /// <summary>
        /// 解析共享返回信息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private Dictionary<string, string> AnalysisQQConnectShareInfo(string json) 
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);

            //权限token
            string ret = obj["ret"].ToString().Replace("\"", "");
            string msg = obj["msg"].ToString().Replace("\"", "");
            dic.Add("ret", ret);
            dic.Add("msg", msg);

            return dic;
        }

        /// <summary>
        /// 解析QQ互联查询授权信息
        /// </summary>
        /// <param name="json"></param>
        //private Dictionary<string, string> AnalysisQQConnectGetTokenInfo(string json)
        //{
        //    Dictionary<string, string> dic = new Dictionary<string, string>();
        //    JObject obj = (JObject)JsonConvert.DeserializeObject(json);
        //    //权限token
        //    string create_at = obj["create_at"].ToString().Replace("\"", "");
        //    string scope = obj["scope"].ToString().Replace("\"", "");
        //    string expires_in = obj["expires_in"].ToString().Replace("\"", "");
        //    string remind_in = obj["appkey"].ToString().Replace("\"", "");
        //    string uid = obj["uid"].ToString().Replace("\"", "");
        //    dic.Add("create_at", create_at);
        //    dic.Add("scope", scope);
        //    dic.Add("expires_in", expires_in);
        //    dic.Add("remind_in", remind_in);
        //    dic.Add("uid", uid);

        //    return dic;
        //}

        /// <summary>
        /// 解析QQ互联的用户基本信息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private Dictionary<string, string> AnalysisQQConnectGetUserInfo(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);

            //返回码
            string ret = obj["ret"].ToString().Replace("\"", "");
            //如果ret<0，会有相应的错误信息提示，返回数据全部用UTF-8编码 
            string msg = obj["msg"].ToString().Replace("\"", "");
            //昵称 
            string nickname = obj["nickname"].ToString().Replace("\"", "");
            //用户头像 大小为30×30像素的头像URL
            string figureurl = obj["figureurl"].ToString().Replace("\"", "");
            //用户头像地址 大小为50×50像素的头像URL
            string figureurl_1 = obj["figureurl_1"].ToString().Replace("\"", "");
            //用户头像地址 大小为100×100像素的头像URL
            string figureurl_2 = obj["figureurl_2"].ToString().Replace("\"", "");
            //性别。如果获取不到则默认返回“男” 
            string gender = obj["gender"].ToString().Replace("\"", "");
            //vip 标识用户是否为黄钻用户（0：不是；1：是） 
            string vip = obj["vip"].ToString().Replace("\"", "");
            //level：黄钻等级 
            string level = obj["level"].ToString().Replace("\"", "");
            //is_yellow_year_vip：标识是否为年费黄钻用户（0：不是； 1：是） 
            string is_yellow_year_vip = obj["is_yellow_year_vip"].ToString().Replace("\"", "");
            dic.Add("ret", ret);
            dic.Add("msg", msg);
            dic.Add("nickname", nickname);
            dic.Add("figureurl", figureurl);
            dic.Add("figureurl_1", figureurl_1);
            dic.Add("figureurl_2", figureurl_2);
            dic.Add("gender", gender);
            dic.Add("vip", vip);
            dic.Add("level", level);
            dic.Add("is_yellow_year_vip", is_yellow_year_vip);

            return dic;
        }

        /// <summary>
        /// 返回请求结果返回值；
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private Dictionary<string, string> AnalysisQQConnectResult(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);

            //返回码
            string ret = obj["ret"].ToString().Replace("\"", "");
            //如果ret<0，会有相应的错误信息提示，返回数据全部用UTF-8编码 
            string msg = obj["msg"].ToString().Replace("\"", "");
            dic.Add("ret", ret);
            dic.Add("msg", msg);

            return dic;
        }
    }
}
